package com.cugmarket.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cugmarket.constant.MessageConstant;
import com.cugmarket.dto.CommentCreateDTO;
import com.cugmarket.dto.CommentPageDTO;
import com.cugmarket.dto.UserDTO;
import com.cugmarket.entity.Comment;
import com.cugmarket.entity.User;
import com.cugmarket.exception.BaseException;
import com.cugmarket.mapper.CommentMapper;
import com.cugmarket.mapper.UserMapper;
import com.cugmarket.service.CommentService;
import com.cugmarket.service.UserService;
import com.cugmarket.utils.UserHolder;
import com.cugmarket.vo.CommentVO;
import com.cugmarket.vo.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static com.cugmarket.constant.MessageConstant.*;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    // 获取某商品的所有评论，并将三级及以上评论平铺到二级评论下
    public List<CommentVO> getComments(String productId) {
        // 获取所有的一级评论
        List<Comment> parentComments = commentMapper.selectParentComments(productId);

        // 将 Comment 转换为 CommentVO
        List<CommentVO> parentVOs = new ArrayList<>();
        for (Comment parentComment : parentComments) {
            CommentVO parentVO = convertToVO(parentComment);
            // 获取所有子评论（包括二级及以上评论），并将它们平级挂在一级评论下面
            List<CommentVO> childVOs = flattenComments(productId, parentComment.getId());
            parentVO.setChildren(childVOs);
            parentVOs.add(parentVO);
        }

        return parentVOs;
    }

    // 将子评论展平成二级评论结构
    private List<CommentVO> flattenComments(String productId, String parentId) {
        // 查询直接回复
        List<Comment> childComments = commentMapper.selectChildComments(productId, parentId);

        // 将 Comment 转换为 CommentVO，并递归获取其子评论
        List<CommentVO> flattenedVOs = new ArrayList<>();
        for (Comment comment : childComments) {
            CommentVO childVO = convertToVO(comment);
            flattenedVOs.add(childVO);
            // 递归获取当前评论的子评论，并将所有子评论都平级添加到列表
            List<CommentVO> childReplies = flattenComments(productId, comment.getId());
            flattenedVOs.addAll(childReplies);
        }

        return flattenedVOs;
    }

    // 添加评论或回复
    public void addComment(Comment comment) {
        // 获取当前登录用户信息
        String userId = UserHolder.getUser();  // 获取当前登录用户 ID
        comment.setPubUserId(userId);  // 设置发布者 ID
        // 通过 userService 获取用户的昵称
        UserDTO user = userService.getUserById(userId);
        comment.setPubNickname(user.getNickName());  // 设置发布者昵称
        comment.setPubAvatar(user.getAvatar());  // 设置发布者头像
        comment.setPubProvince(user.getProvince());  // 设置发布者省份
        // 保存评论
        boolean saveResult = save(comment);

        if (!saveResult) {
            throw new BaseException(COMMENT_SAVE_ERROR);  // 保存失败时抛出自定义异常
        }
    }

    @Override
    public PageVO getCommentsByPage(CommentPageDTO commentPageDTO) {
        // 从 DTO 中提取参数
        String productId = commentPageDTO.getProductId();
        int pageNum = commentPageDTO.getPageNum();
        int pageSize = commentPageDTO.getPageSize();

        // 使用 PageHelper 对一级评论进行分页
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> parentComments = commentMapper.selectParentComments(productId);

        // 将 Comment 转换为 CommentVO，并处理子评论
        List<CommentVO> parentVOs = new ArrayList<>();
        for (Comment parentComment : parentComments) {
            CommentVO parentVO = convertToVO(parentComment);

            // 获取所有子评论（平级挂在一级评论下）
            List<CommentVO> childVOs = flattenComments(productId, parentComment.getId());
            parentVO.setChildren(childVOs);

            parentVOs.add(parentVO);
        }

        // 使用 PageInfo 获取分页的元数据
        PageInfo<CommentVO> pageInfo = new PageInfo<>(parentVOs);

        // 构建 PageVO 对象并返回
        PageVO pageVO = new PageVO();
        pageVO.setTotal(pageInfo.getTotal()); // 总记录数
        pageVO.setRecords(pageInfo.getList()); // 当前页数据

        return pageVO;
    }


    // 工具方法：将 Comment 转换为 CommentVO
    private CommentVO convertToVO(Comment comment) {
        CommentVO commentVO = new CommentVO();
        BeanUtils.copyProperties(comment, commentVO);
        return commentVO;
    }
}
